from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class ZYH(Device, DeviceCost):
    """
    305 专用换包站台
    专用换(ZYH)
    """
    COST_TIME = 10
    # 资源
    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.COST_TIME


class ZYHSystem(System):
    """
    专用拆包区 系统
    """
    # 拆包区数量
    ZYH_NUMS = 2

    # 拆包区列表
    zyh_list: list[ZYH] = []

    def __init__(self, env: Environment, name: str, code: str = None):
        super().__init__(env, name, code)
        self.__init_zyh_list()

    def __init_zyh_list(self):
        """
        初始化ZYH列表
        :param env:
        :return:
        """
        self.zyh_list = [ZYH(self.env, f'专用换-{_ + 1}') for _ in range(self.ZYH_NUMS)]

    def run_task(self, task: Task):
        if not self.zyh_list:
            while self.running:
                yield self.env.timeout(1)
                if self.zyh_list:
                    break
        #
        zyh = self.zyh_list.pop(0)
        with zyh.resource.request() as req:
            yield req
            #
            process = task.process
            process.begin_ts = self.env.now
            process.begin_pos = zyh.name
            yield self.env.timeout(zyh.cost())
            process.end_ts = self.env.now
            process.device_code = zyh.name
            # TODO: 根据任务类型 将任务分配至不同的下一个流程
            process.end_pos = None
        #
        self.zyh_list.append(zyh)
